package com.zjw.zy.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.zjw.zy.base.BaseViewModel
import com.zjw.zy.bean.BindLoveInfo
import com.zjw.zy.bean.User
import com.zjw.zy.bean.WsMessage
import com.zjw.zy.constant.AppConstant
import com.zjw.zy.constant.AppConstant.APP_ME_ACCESS_KEY
import com.zjw.zy.constant.BindLoveState
import com.zjw.zy.constant.RegisterUserResult
import com.zjw.zy.ext.launchInIo
import com.zjw.zy.ext.requireService
import com.zjw.zy.ext.shortToast
import com.zjw.zy.smi.JustWithIt
import com.zjw.zy.utils.AppUtils
import com.zjw.zy.utils.GsonUtils
import com.zjw.zy.utils.LogUtils
import com.zjw.zy.utils.SharePrefUtils
import remotecall.RemoteCallManager

/**
 * @author     ：zhong.jw
 * @date       ：Created in 2022/10/20 9:36
 * @description：
 */
class AccessViewModel : BaseViewModel() {

    companion object {
        private const val TAG = "AccessViewModel"
    }

    private val mIdInfo = MutableLiveData<User>()
    fun getIdInfo(): LiveData<User> = mIdInfo

    private val mBindInfo = MutableLiveData<BindLoveInfo>()
    fun getBindInfo(): LiveData<BindLoveInfo> = mBindInfo

    fun emitUser(info: User) {
        mIdInfo.postValue(info)
    }


    fun finishAccess(msg: WsMessage, isVisitor: Boolean) {
        launchInIo {
            val self = mIdInfo.value ?: return@launchInIo

            self.loveUsername = if (isVisitor) {
                msg.to
            } else {
                msg.from
            }
            requireService()?.requestLover(
                self,
                RemoteCallManager.defaultImpl().remoteCall<User> { lover ->
                    LogUtils.d(TAG, "finishAccess")

                    val bindLoveInfo = msg.castPayload(BindLoveInfo::class.java)
                    self.putInfo(User.BIND_INFO_KEY, bindLoveInfo)

                    SharePrefUtils.putString(APP_ME_ACCESS_KEY, GsonUtils.toJson(self))
                    SharePrefUtils.putString(
                        AppConstant.APP_LOVER_ACCESS_KEY,
                        GsonUtils.toJson(lover)
                    )
                    //finish
                    SharePrefUtils.putBoolean(AppConstant.IS_APP_ACCESS, true)

                    mBindInfo.postValue(bindLoveInfo)
                })
        }
    }


    private val registerResult = MutableLiveData<Int>()
    fun getRegisterResult(): LiveData<Int> = registerResult

    fun registerAccess(username: String, address: String, name: String) {
        launchInIo {
            val user = User()
            user.username = username
            user.address = address
            user.name = name

            requireService()?.registerAccess(user, RemoteCallManager.defaultImpl().remoteCall<Int> {
                //存储到数据库
                if (it == RegisterUserResult.SUCCESS || it == RegisterUserResult.REGISTERED) {
                    launchInIo {
                        //存储到Share中
                        SharePrefUtils.putString(APP_ME_ACCESS_KEY, GsonUtils.toJson(user))
                        emitUser(user)
                    }
                }
                registerResult.postValue(it)
            })
        }
    }

    fun rejectInvite(bindMessage: WsMessage) {
        launchInIo {
            bindMessage.castPayload(BindLoveInfo::class.java).apply {
                this.state = BindLoveState.BIND_REJECT
                this.accept = false
            }
            bindMessage.jsonPayload()
            requireService()?.sendWsMessage(bindMessage)
        }
    }

    fun accept(bindMessage: WsMessage) {
        launchInIo {
            bindMessage.castPayload(BindLoveInfo::class.java).apply {
                this.accept = true
                this.state = BindLoveState.BIND_REQUEST_CODE
            }
            bindMessage.jsonPayload()
            requireService()?.sendWsMessage(bindMessage)
        }
    }

    fun passCheckCode(bindMessage: WsMessage) {
        launchInIo {
            bindMessage.castPayload(BindLoveInfo::class.java).apply {
                this.accept = true
                this.state = BindLoveState.BIND_PASS_CODE
            }
            bindMessage.jsonPayload()
            requireService()?.sendWsMessage(bindMessage)
        }
    }

    fun checkBindStatus(): LiveData<User> {
        val result = MutableLiveData<User>()
        launchInIo {
            mIdInfo.value?.apply {
                requireService()?.requestLover(
                    this,
                    RemoteCallManager.defaultImpl().remoteCall<User> { lover ->
                        if (lover != null) {
                            //已绑定过
                            //lover
                            SharePrefUtils.putString(
                                AppConstant.APP_LOVER_ACCESS_KEY,
                                GsonUtils.toJson(lover)
                            )

                            lover.getInfo(User.BIND_INFO_KEY, BindLoveInfo::class.java)?.apply {
                                mBindInfo.postValue(this)
                            }

                            SharePrefUtils.putString(
                                AppConstant.APP_ME_ACCESS_KEY,
                                GsonUtils.toJson(this)
                            )
                            //finish
                            SharePrefUtils.putBoolean(AppConstant.IS_APP_ACCESS, true)

                            result.postValue(AppUtils.getSelf())
                        }
                    })
            }
        }
        return result
    }

}